import Taro from "@tarojs/taro";
import {
	$Req
} from '@utils'
/**
 * 用户信息
 * 包括一些公共调用
 * **/

const userData = Taro.getStorageSync("userInfo");


export default {
	/** store数据 **/
	state: {
		// 全局弹框控制
		isOpen: false,
		userInfo: userData ? JSON.parse(userData) : {}
	},
	/** reducers **/
	reducers: {
		setStatus(state, payload) {
			return {
				...state,
				...payload
			};
		},
		setUserInfo(state, payload) {
			state.userInfo = payload;
			Taro.setStorageSync("userInfo", JSON.stringify(payload));
			return {
				...state
			};
		},
	},
	/** actions 可以是一个对象，也可以是一个函数，函数的第1个参数自动被注入dispatch **/
	effects: {
		/** 模拟获取用户信息 **/
		async getUserInfo(params = {}) {
			const {
				code,
				msg,
				data
			} = await $Req({
				url: '',
				type: 'post',
				data: {},
			})
			if (code === 200) {
				this.setStatus({
					userInfo: data
				})
				return data;
			}
		},
		/** 获取微信用户信息 **/
		async getWxUserInfo(params = {}) {
			if (!params.rawData || !params.encryptedData) {
				return;
			}
			Taro.showToast({
				title: '处理中',
				icon: 'loading',
				duration: 3000
			})
			const {
				encryptedData,
				iv,
				rawData,
				session_key
			} = params;
			const resLogin = await Taro.login();
			
			// 去除特殊表情
			let aaa = JSON.parse(rawData);
			aaa.nickName = aaa.nickName.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig, "")

			const postData = {
				code: resLogin.code,
				encryptedData,
				iv,
				userInfo: JSON.stringify(aaa)
				// session_key
			}
			
			// 获取分享信息
			let shareId = Taro.getStorageSync("shareId");
			console.log("登录时：shareId：" + shareId);
			
			if (shareId) {
				postData.shareUserId = shareId;
			}

			let {
				code,
				message,
				data
			} = await $Req({
				type: "post",
				url: "/user/wx_login",
				data: postData,
			});
			if (!data) return;

			Taro.setStorageSync("token", data.token);
			let userInfo = data;
			userInfo.code = resLogin.code
			userInfo.session_key = data.sessionKey;
			userInfo.username = data.name;
			
			delete userInfo.name;
			delete userInfo.sessionKey;

			let add = await $Req({
				type: "get",
				url: "/indexUser/getShippingAddress",
				data: {
					userId: userInfo.userId
				},
			});

			if (!add.data) return;

			add.data.forEach(el => {
				if (el.defaultFlag) {
					Taro.setStorageSync("address", el);
				}
			});

			Taro.removeStorageSync("shareId")
			if (data.phone) {
				Taro.setStorageSync("userPhone", data.phone);
			}

			this.setUserInfo(userInfo);
			return userInfo;
		},
	}
};